package org.csu.secondhand.util;

import com.alibaba.fastjson.*;
import okhttp3.*;

import java.io.*;

public class UploadUtil {
    public static final String API_TYPE = "bilibili";
    public static final String PRIVATE_STORAGE = "oss";
    public static final String TOKEN = "28775f8237b0f5f6d0e958807f8bcfed";
    public static final String URL = "https://www.hualigs.cn/api/upload";

    //第二步、发送请求
    public static JSONObject uploadImg(File image) {
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), image);
        OkHttpClient client = new OkHttpClient();
        JSONObject jsonObject = null;
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", image.getName(), fileBody)
                .addFormDataPart("apiType", API_TYPE)
                .addFormDataPart("privateStorage", PRIVATE_STORAGE)
                .addFormDataPart("token", TOKEN)
                .build();
        Request request = new Request.Builder()
                .url(URL)
                .post(requestBody)
                .build();
        Response response;
        try {
            response = client.newCall(request).execute();
            String jsonString = response.body().string();
            System.out.println(jsonString);
            jsonObject = JSON.parseObject(jsonString);
            if (!jsonObject.getString("code").equals("200")) {
                System.out.println("失败");
            } else {
                System.out.println("成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    //第一步、获取流文件
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //第三步、获得图片URL
    public static String getUrl(File file) {
        return uploadImg(file).getJSONObject("data").getJSONObject("url").getString(API_TYPE);
    }

    public static void main(String[] args) {
        File file = new File("C:\\Users\\vivi\\Desktop\\1.png");
        String url = getUrl(file);
        System.out.println(url);
    }

}
